package com.dora.basic.juc.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Cas例子
 *
 * @author hanchen
 * @date 2024/02/21
 */
public class CasExample {
    private static final AtomicInteger COUNT = new AtomicInteger(0);

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                int oldValue, newValue;
                do {
                    // 读取当前值
                    oldValue = COUNT.get();
                    // 预期值 +1
                    newValue = oldValue + 1;
                    // CAS 操作，如果旧值等于当前值，则更新为新值
                } while (!COUNT.compareAndSet(oldValue, newValue));
                System.out.println(Thread.currentThread().getName() + ": " + newValue);
            }).start();
        }
    }
}
